package com.jmm;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * volatile不保证原子性测试，操作的同时也可能被其他线程操作
 */
public class VDemo2 {

    private volatile static AtomicInteger num = new AtomicInteger(0);

    public static void main(String[] args) {

        for (int i = 0; i < 20; i++) {
            new Thread(() -> {
                for (int j = 0; j < 1000; j++) {
                    add();
                }
            }).start();
        }

        while (Thread.activeCount() > 2) {
            Thread.yield();
        }
        System.out.println(Thread.currentThread().getName() + "  " + num);

    }

    public static void add() {
        num.getAndIncrement();  // AtomicInteger  +1方法  ，底层为CAS
    }

}
